package org.shiki.hrm.service.impl;

import org.shiki.hrm.domain.LoginUser;
import org.shiki.hrm.domain.VipUser;
import org.shiki.hrm.dto.RegDto;
import org.shiki.hrm.feign.LoginUserFeignClient;
import org.shiki.hrm.mapper.VipUserMapper;
import org.shiki.hrm.service.IVipUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.shiki.hrm.util.AjaxResult;
import org.shiki.hrm.util.BitStatesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author shiki
 * @since 2022-03-18
 */
@Service
public class VipUserServiceImpl extends ServiceImpl<VipUserMapper, VipUser> implements IVipUserService {
	@Autowired
	private VipUserMapper vipUserMapper;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private LoginUserFeignClient client;

	@Override
	public AjaxResult registory(RegDto regDto) {
		// 校验短信验证码
		Object o = redisTemplate.opsForValue().get("USER-REG" + regDto.getMobile());
		Assert.notNull( o, "验证码已过期!");
		Assert.isTrue(regDto.getSmsCode().equals(o.toString()), "验证码错误!");
		String mobile = regDto.getMobile();
		String password = regDto.getPassword();
		// 调用auth服务,保存用户信息
		LoginUser loginUser = new LoginUser();
		loginUser.setUsername(mobile);
		loginUser.setPassword(password);
		AjaxResult result = client.register(loginUser);
		Assert.isTrue(result.isSuccess(), result.getMessage());
		// 保存t_vip_user
		VipUser vipUser = new VipUser();
		vipUser.setPhone(mobile);
		vipUser.setPassword(password);
		vipUser.setCreateTime(System.currentTimeMillis());
		// loginId数据类型转换为Long
		Integer resultObj = (Integer) result.getResultObj();
		vipUser.setLoginId(Long.valueOf(resultObj));
		// 设置状态
		long state = BitStatesUtils.addState(BitStatesUtils.OP_REGISTED, BitStatesUtils.OP_ACTIVED);
		state = BitStatesUtils.addState(state, BitStatesUtils.OP_AUTHED_PHONE);
		vipUser.setBitState(state);
		// 保存
		vipUserMapper.insert(vipUser);
		return result;
	}
}
